<?php
namespace App\Services;

abstract class HttpAbstract
{

	/**
	 * 基础URL
	 */
	protected $base_url;

	/**
	 * HTTP请求超时时间
	 */
	protected $timeout = 50;

	/**
	 * GET方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpGet($url, $data = [])
	{
		return $this->httpRequest('GET', $url, $data);
	}

	/**
	 * POST方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpPost($url, $data = [])
	{
		return $this->httpRequest('POST', $url, $data);
	}

	/**
	 * 基础HTTP请求实现
	 * @param string $method
	 * @param string $url
	 * @param array $data
	 * @return string
	 */
	private function httpRequest($method, $url, $data)
	{
		$method = strtoupper($method);
		if (! in_array($method, [
			'GET',
			'POST'
		])) {
			$method = 'GET';
		}

		if (! preg_match('#^https?://#i', $url)) {
			if ($url{0} === '/') {
				$url = substr($url, 1);
			}
			$url = str_finish($this->base_url, '/') . $url;
		}

		$response = false;
		try {

			$data = http_build_query($data);

			$opts = [
				'http' => [
					'method' => $method,
					'timeout' => $this->timeout
				]
			];

			switch ($method) {
				case 'GET':
					$url .= strpos($url, '?') === false ? '?' : '&';
					$url .= $data;
					break;
				case 'POST':
					$opts['http']['header'] = "Content-type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($data) . "\r\n";
					$opts['http']['content'] = $data;
					break;
			}

			$context = stream_context_create($opts);
			$response = file_get_contents($url, false, $context);
		} catch (\Exception $e) {
			// 捕获异常。
			// throw $e;
			// TODO: 记录错误日志，静默处理。
		}

		// 剔除前后空格。
		$response = preg_replace('/^\\s+|\\s+$/', '', $response);

		return $response;
	}
}
